package cn.lanchengkeji.datafillingsystem.service.impl;



import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.Roles;
import cn.lanchengkeji.datafillingsystem.entity.UserRole;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.exception.ParameterInvalidException;
import cn.lanchengkeji.datafillingsystem.exception.UserDuplicateException;
import cn.lanchengkeji.datafillingsystem.mapper.UsersMapper;
import cn.lanchengkeji.datafillingsystem.service.IRolesService;
import cn.lanchengkeji.datafillingsystem.service.IUserRoleService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import cn.lanchengkeji.datafillingsystem.vo.ExportUserListVO;
import cn.lanchengkeji.datafillingsystem.vo.ExportWebUserListVO;
import cn.lanchengkeji.datafillingsystem.vo.UsersVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Resource
    private IUserRoleService iUserRoleService;

    @Resource
    private IRolesService iRolesService;

    @Override
    public Users getUserByName(String userName) {
        UsersVO condition = new UsersVO();
        condition.setUserName(userName);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(condition);
        Users users = this.getOne(queryWrapper);
        return users;
    }

    /**
     * 添加用户
     *
     * @param users
     * @return
     * @throws Exception
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public boolean insertUsers(UsersVO users) throws Exception {
        if (Utils.isEmpty(users)) {
            throw new ParameterInvalidException();
        }
        List<Users> searchUsers;

        // 判断用户名是否重复
        if (Utils.notEmpty(users.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, users.getUserName());
            searchUsers = this.list(condition);
            if (searchUsers.size() > 0) {
                throw new UserDuplicateException();
            }
        }

        // 添加用户
        boolean createUserFlag = this.save(users);

        // 添加角色
        Integer roleId = users.getRoleIds().get(0);

        UserRole userRole = new UserRole();
        userRole.setUserId(users.getId());
        userRole.setRoleId(roleId);
        boolean saved = iUserRoleService.save(userRole);
        return createUserFlag && saved;
    }

    /**
     * 修改用户
     *
     * @param users
     * @return
     * @throws Exception
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean updateUsers(UsersVO users) throws Exception {

        if (Utils.isEmpty(users) || Utils.isEmpty(users.getId())) {
            return new ResponseBean(StatusCode.IS_NULL, users);
        }

        // 查询用户是否存在
        Users oUser = this.getById(users.getId());
        if (Utils.isEmpty(oUser)) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, users);
        }
        if (oUser.getDelFlag().equals(1)) {
            return new ResponseBean(StatusCode.USER_DELETE, users);
        }

        List<Users> searchUsers;

        // 判断除本身外用户名是否重复
        if (Utils.notEmpty(users.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, users.getUserName()).ne(Users.ID, users.getId());
            searchUsers = this.list(condition);
            if (searchUsers.size() > 0) {
                return new ResponseBean(StatusCode.USER_NAME_REPEAT, users);
            }
        }

        // 如果新密码不为空，则判断原密码是否正确
        if (Utils.notEmpty(users.getNewPasswd()) && !users.getOldPasswd().equals(oUser.getPasswd())) {
            return new ResponseBean(StatusCode.USER_PWD_ERROR, users);
        } else {
            users.setPasswd(users.getNewPasswd());
        }

        // 修改用户
        boolean updateUserFlag = this.saveOrUpdate(users);
        boolean updateUserRoleFlag = true;
        if (updateUserFlag) {
            // 查出当前用户角色
            Integer roleId = users.getRoleIds().get(0);
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(UserRole.USER_ID, users.getId());
            UserRole one = iUserRoleService.getOne(queryWrapper);
            // 存入新的角色
            one.setRoleId(roleId);
            // 更新
            updateUserRoleFlag = iUserRoleService.updateById(one);
        }

        if (!updateUserFlag || !updateUserRoleFlag) {
            // 回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return new ResponseBean(StatusCode.OK, users);
    }

    /**
     * 修改客户端用户
     *
     * @param users
     * @return
     * @throws Exception
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean updateWebUsers(UsersVO users) throws Exception {

        // 查询用户是否存在
        Users oUser = this.getById(users.getId());
        if (Utils.isEmpty(oUser)) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, users);
        }
        if (oUser.getDelFlag().equals(1)) {
            return new ResponseBean(StatusCode.USER_DELETE, users);
        }

        List<Users> searchUsers;

        // 判断除本身外用户名是否重复
        if (Utils.notEmpty(users.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, users.getUserName()).ne(Users.ID, users.getId());
            searchUsers = this.list(condition);
            if (searchUsers.size() > 0) {
                return new ResponseBean(StatusCode.USER_NAME_REPEAT, users);
            }
        }

        // 如果新密码不为空，则判断原密码是否正确
        if (Utils.notEmpty(users.getNewPasswd()) && !users.getOldPasswd().equals(oUser.getPasswd())) {
            return new ResponseBean(StatusCode.USER_PWD_ERROR, users);
        } else {
            users.setPasswd(users.getNewPasswd());
        }

        // 修改用户
        boolean updateUserFlag = this.saveOrUpdate(users);

        return new ResponseBean(StatusCode.OK, users);
    }

    /**
     * 用户未登录状态下修改用户信息
     *
     * @param users
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean updateUsersByUserName(UsersVO users) throws Exception {

        if (Utils.isEmpty(users) || Utils.isEmpty(users.getId())) {
            return new ResponseBean(StatusCode.IS_NULL, users);
        }

        // 查询用户是否存在
        Users oUser = this.getById(users.getId());
        if (Utils.isEmpty(oUser)) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, users);
        }
        if (oUser.getDelFlag().equals(1)) {
            return new ResponseBean(StatusCode.USER_DELETE, users);
        }

        List<Users> searchUsers;

        // 判断除本身外用户名是否重复
        if (Utils.notEmpty(users.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, users.getUserName()).ne(Users.ID, users.getId());
            searchUsers = this.list(condition);
            if (searchUsers.size() > 0) {
                return new ResponseBean(StatusCode.USER_NAME_REPEAT, users);
            }
        }

        // 如果新密码不为空，则判断原密码是否正确
        if (Utils.notEmpty(users.getNewPasswd()) && !users.getOldPasswd().equals(oUser.getPasswd())) {
            return new ResponseBean(StatusCode.USER_PWD_ERROR, users);
        } else {
            users.setPasswd(users.getNewPasswd());
        }

        // 修改用户
        boolean updateUserFlag = this.saveOrUpdate(users);

        return new ResponseBean(StatusCode.OK, users);
    }

    /**
     * 删除用户
     *
     * @param users 根据id删除菜单
     * @return
     * @throws Exception
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ResponseBean deleteUsers(Users users) throws Exception {

        // 判断当前用户是否存在
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Users.ID, users.getId());
        Users oUsers = this.getOne(queryWrapper);
        if (Utils.isEmpty(oUsers)) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
        }

        // 逻辑删除当前用户
//        oUsers.setDelFlag(1);

        // 物理删除当前用户
        if (this.removeById(oUsers.getId())) {

            // 删除当前用户的角色关系
            QueryWrapper<UserRole> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(UserRole.USER_ID, oUsers.getId());
            iUserRoleService.remove(queryWrapper1);

            return new ResponseBean(StatusCode.OK, oUsers);
        } else {
            return new ResponseBean(StatusCode.OK_FAIL, oUsers);
        }
    }

    /**
     * 查看单个用户
     *
     * @param users
     * @return
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    public UsersVO selectOneUsers(UsersVO users) throws InvocationTargetException, IllegalAccessException {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Users.CHECK_FLAG, 3);
        queryWrapper.eq(Users.ID, users.getId());
        Users nUser = this.getById(queryWrapper);

        // 查询已添加的角色
        List<Roles> rolesList = iRolesService.getRolesByUser(users.getId());
        UsersVO usersVO = new UsersVO();
        org.apache.commons.beanutils.BeanUtils.copyProperties(usersVO, nUser);
        usersVO.setYtjRoles(rolesList);

        // 查询未添加的角色
//        List<Roles> rolesList1 = iRolesService.getWtjRolesByUser(users.getId());
//        nUser.setWtjRoles(rolesList1);

        return usersVO;
    }

    /**
     * 分页查看用户
     *
     * @param page      分页器
     * @param condition 查询条件
     * @return
     * @author yuhao
     * @version 2018-12-05 11:52
     */
    @Override
    public Page<UsersVO> pageUsers(Page<UsersVO> page, UsersVO condition) {

        List<UsersVO> usersList = baseMapper.findUsers(page, condition);
        for (UsersVO users : usersList) {

            // 查询已添加的角色
            List<Roles> rolesList = iRolesService.getRolesByUser(users.getId());
            users.setYtjRoles(rolesList);
        }
        page.setRecords(usersList);

        return page;
    }

    @Override
    public Page<UsersVO> pageWebUsers(Page page, UsersVO condition) {
        page = baseMapper.findWebUsersIds(page, condition);
        List<UsersVO> webUsers = baseMapper.findWebUsers(page.getRecords());
        return page.setRecords(webUsers);
    }

    @Override
    public Page<UsersVO> pageCheckUsers(Page<UsersVO> page, UsersVO condition) {

        List<UsersVO> usersList = baseMapper.findCheckUsers(page, condition);
        for (UsersVO users : usersList) {

            // 查询已添加的角色
            List<Roles> rolesList = iRolesService.getRolesByUser(users.getId());
            users.setYtjRoles(rolesList);

        }
        page.setRecords(usersList);

        return page;
    }

    /**
     * 根据角色id查询用户
     *
     * @param roleId
     * @return
     * @author yuhao 2018-12-07 15:56
     */
    @Override
    public List<Users> selectUsersByRoleId(Integer roleId) {
        return baseMapper.selectUsersByRoleId(roleId);
    }

    /**
     * 查看单个用户
     *
     * @param users
     * @return
     */
    @Override
    public UsersVO selectUserInfo(UsersVO users) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Users.CHECK_FLAG, Const.USER_CHECK_PASS_3);
        queryWrapper.eq(Users.ID, users.getId());
        Users nUser = this.getOne(queryWrapper);

        // 查询已添加的角色
        List<Roles> rolesList = iRolesService.getRolesByUser(users.getId());
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(nUser, usersVO);
        usersVO.setYtjRoles(rolesList);

        return usersVO;
    }

    @Override
    public List<ExportUserListVO> getExportUserListVO() {
        return baseMapper.getExportUserListVO();
    }

    @Override
    public List<ExportWebUserListVO> getExportWebUserListVO() {
        return baseMapper.getExportWebUserListVO();
    }
}
